import { Collapse, CollapseProps, Form, Input, InputNumber, Radio, Select, Switch } from "antd";
import { useEffect, useState } from "react";
import { ComponentConfig, ComponentSetter, useComponentConfigStore } from "@/stores/low-editor-comps-conf";
import { useComponentsStore } from "@/stores/edit-pages-store";
import {
  TablePaginationSelector,
  InterfaceConfSelector,
  ApiFieldSelector,
  TableColumnSelector
} from "@/pages/lowCodeEditorPlus/components/Setting/selectors";
import { FormulaEditor } from "../selectors/FormulaEditor";

export function ComponentAttr() {
  const [form] = Form.useForm();

  const { curComponentId, curComponent, updateComponentProps, updateComponentAlias } = useComponentsStore();
  const { flatComponentConfig } = useComponentConfigStore();
  const componentConfig = flatComponentConfig();
  const [otherMenuItems, setOtherMenuItems] = useState<CollapseProps["items"]>([]);
  
  const propsSetterConf = componentConfig[curComponent!.name]?.setter || [];
  const activeKeys: string[] = propsSetterConf.map(mItem=>mItem.key).concat("basicMessage")
  
  useEffect(() => {
    if (curComponent) {
      form.resetFields();
      const basicDefaultValues = (componentConfig[curComponent.name]?.defaultProps ?? {})
      // const basicDefaultValues = (componentConfig[curComponent.name]?.setter ?? []).reduce(
      //   (sum, cell) => {
      //     if (cell?.defaultValue) {
      //       sum[cell.name] = cell.defaultValue;
      //     }
      //     return sum;
      //   },
      //   {} as Record<string, any>
      // );
      // form.setFieldsValue({ ...data, ...basicDefaultValues?.basicDefaultValues, ...curComponent?.props});
      form.setFieldsValue({ ...basicDefaultValues?.basicDefaultValues, ...curComponent?.props});
      
      setOtherMenuItems(
        propsSetterConf.filter(mItem=>mItem.children.length>0).map((mItem)=>{
          return {
            key: mItem.key,
            label: mItem.label,
            children: (
              <div key={mItem.key}>
                {mItem.children.map(sItem => (
                  <Form.Item key={sItem.name} name={sItem.name} label={sItem.label}>
                    {renderFormElement(sItem)}
                  </Form.Item>
                ))}
              </div>
            ),
          }
        })
      )
    }
  }, [curComponent]);

  if (!curComponentId || !curComponent) return null;

  function renderFormElement(setting: ComponentSetter) {
    const { type, options, props } = setting;
    const {defaultChecked} = props || {};
    if (type === "select") {
      return <Select options={options} />;
    } else if (type === "input") {
      return <Input />;
      // return <FormulaEditor/>
    } else if (type === "switch") {
      return <Switch defaultChecked={defaultChecked}/>;
    } else if (type === "radio") {
      return <Radio.Group optionType="button" buttonStyle="solid" options={options} className="compactButton"/>
    } else if (type === "inputNumber") {
      return <InputNumber className="w-full"/>;
    } else if (type === "tablePaginationSelector"){
      return <TablePaginationSelector/>
    } else if ( type ==="apiSelector"){
      return <InterfaceConfSelector/>
    } else if ( type === "apiFieldSelector"){
      return <ApiFieldSelector {...props}/>
    } else if ( type === "tableColumnSelector"){
      return <TableColumnSelector/>
    }
  }
  function handleAliasChange(e: React.ChangeEvent<HTMLInputElement>) {
    const newAlias = e.target.value;
    if (curComponentId) {
      updateComponentAlias(curComponentId, newAlias);
    }
  }
  function propsChange(changeValues: Partial<ComponentConfig>) {
    console.log("🚀 ~ valueChange ~ changeValues:", changeValues);
    if (curComponentId) {
      updateComponentProps(curComponentId, changeValues);
    }
  }

  const menuItems = [
    {
      key: "basicMessage",
      label: "基本信息",
      children: (
        <div>
          <Form.Item label="组件id">
            <Input value={curComponent.id} disabled />
          </Form.Item>
          <Form.Item label="组件类型">
            <Input value={curComponent.name} disabled />
          </Form.Item>
          <Form.Item label="组件名称">
            <Input value={curComponent.desc} disabled />
          </Form.Item>
          <Form.Item label="组件别名">
            <Input value={curComponent.alias} onChange={handleAliasChange} />
          </Form.Item>
        </div>
      ),
    },
    ...(otherMenuItems || [])
    // {
    //   key: "headerTool",
    //   label: "头部工具栏",
    //   children: (
    //     <div key="headerTool">
    //        <Form.Item key="filterFields" name="filterFields" label="查询字段">
    //        <ApiFieldSelector/>
    //         </Form.Item>
    //     </div>
    //   ),
    // }
  ]
  return (
    <Form
      form={form}
      onValuesChange={propsChange}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      labelAlign="left"
      labelWrap
      colon={false}
      className="smallText"
    >
      <Collapse
        defaultActiveKey={activeKeys}
        ghost
        items={menuItems}
        expandIconPosition="end"
        className="classic headerGray"
      />
    </Form>
  );
}
